package javaCode.chapter12.arrays_;

import java.util.Arrays;
import java.util.Comparator;

/**
 * @author 徐州城
 * @version 1.0
 */
public class ArraysExercise01 {
    public static void main(String[] args) {
        Book[] books = new Book[4];
        books[0] = new Book("红楼梦~",100);
        books[1] = new Book("金瓶梅~",99);
        books[2] = new Book("疯狂阅读~",10);
        books[3] = new Book("Java从入门到放弃~",200);

        Arrays.sort(books, new Comparator() {
            @Override
            public int compare(Object o1,Object o2) {
                Book b1 = (Book) o1;
                Book b2 = (Book) o2;
                double priceVal = b2.getPrice() - b1.getPrice();
                if (priceVal > 0)
                    return 1;
                else if (priceVal < 0)
                    return -1;
                else
                    return 0;
            }
        });
        System.out.println(Arrays.toString(books));

        //按照书名的长度经行排序
        Arrays.sort(books, new Comparator() {
            @Override
            public int compare(Object o1, Object o2) {
                Book b1 = (Book) o1;
                Book b2 = (Book) o2;
//                return b2.getName().length() > b1.getName().length() ? 1 : -1;
                return b2.getName().length() - b1.getName().length();
            }
        });
        System.out.println(Arrays.toString(books));
    }
}

/*
案例：自定义Book类，里面包含 name和price，按price排序(从大到小)。要求使用两种方式排序，有一个 Book[] books = 4本书对象
使用前面学习的传递 实现Comparator接口匿名内部类，也称为定制排序
 */
class Book{
    private String name;
    private double price;

    public Book(String name, int price) {
        this.name = name;
        this.price = price;
    }

    @Override
    public String toString() {
        return "Book{" +
                "name='" + name + '\'' +
                ", price=" + price +
                '}';
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public double getPrice() {
        return price;
    }

    public void setPrice(int price) {
        this.price = price;
    }
}